package cn.promonkey.core.toolkit;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** @author gongym */
public class JsonUtils {
  private static final ObjectMapper MAPPER = new ObjectMapper();
  /** 序列化中的时间格式化 */
  private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

  @SuppressWarnings("Duplicates")
  public static String objectToJson(Object data) {
    try {
      MAPPER.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_FORMAT));
      return MAPPER.writeValueAsString(data);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }

  @SuppressWarnings("Duplicates")
  public static String objectToJson(Object data, String dateFormat) {
    try {
      MAPPER.setDateFormat(new SimpleDateFormat(dateFormat));
      return MAPPER.writeValueAsString(data);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }

  public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
    try {
      return MAPPER.readValue(jsonData, beanType);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  @SuppressWarnings("Duplicates")
  public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
    JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    try {
      return MAPPER.readValue(jsonData, javaType);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  @SuppressWarnings("Duplicates")
  public static <T> List<T> jsonToList(String jsonData) {
    JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, Map.class);
    try {
      return MAPPER.readValue(jsonData, javaType);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public static HashMap<Object, Object> jsonToMap(String jsonData) {
    try {
      return MAPPER.readValue(jsonData, new TypeReference<HashMap<Object, Object>>() {});
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * @Author wultn
   * @Date 15:03 2020/8/12
   * @Param [obj]
   * @return java.util.List<java.lang.Long>
   **/
  public static List<Long> ObjectToList(Object obj) {
    List<Long> result = new ArrayList<Long>();
    if (obj instanceof List<?>) {
      for (Object o : (List<?>) obj) {
        Integer id = (Integer) o;
        result.add(id.longValue());
      }
      return result;
    }
    return null;
  }
}
